package cn.fl.esign.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.esign.service.IFilSignService;
import cn.fl.esign.vo.FilSignVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import tc.esign.facade.esign.condition.FilSignQueryCondition;
import tc.esign.facade.esign.dto.FilSignDTO;

/**
 * @Description: 合同签署表 控制层
 */
@Controller
@RequestMapping("/esign/filSign")
public class FilSignController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FilSignController.class);

	/**
	 * FilSign 服务层BEAN
	 */
	@Autowired
	private IFilSignService filSignService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("esign/filEsign/filEsignList");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("esign/filSign/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		FilSignQueryCondition qc = new FilSignQueryCondition();
		String contractNm = request.getParameter("contractNm");
		String contractCode = request.getParameter("contractCode");
		String signSts = request.getParameter("signSts");
		String signName = request.getParameter("signName");
		String signNm = request.getParameter("signNm");
		String orgNm = request.getParameter("orgNm");
		if (StringUtils.isNotEmpty(contractNm)) {
			qc.setContractNm(contractNm);
		}
		if (StringUtils.isNotEmpty(contractCode)) {
			qc.setContractCode(contractCode);
		}
		if (StringUtils.isNotEmpty(signSts)) {
			qc.setSignSts(Integer.parseInt(signSts));
		}
		if (StringUtils.isNotEmpty(signName)) {
			qc.setSignName(signName);
		}
		if (StringUtils.isNotEmpty(signNm)) {
			qc.setSignNm(signNm);
		}
		if (StringUtils.isNotEmpty(orgNm)) {
			qc.setOrgNm(orgNm);
		}
		page.setCondition(qc);

		//TODO SOMETHING
		//Pager pager = new Pager();//this.filSignService.searchListPage(page);
		Pager pager =this.filSignService.searchListPage(page);
		List<FilSignVO> list = (List<FilSignVO>) pager.getResultList();
		ListPageVO<FilSignVO> listPage = new ListPageVO<FilSignVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.filSignService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			FilSignVO vo = this.filSignService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		FilSignVO entity = null;
		try {
			entity = new FilSignVO();
			//TODO ADD PARAM
			Long id = this.filSignService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FilSignVO entity = null;
		try {
			entity = new FilSignVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.filSignService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 上传签署模板
	 */
	@RequestMapping(value = "/getUpPdf.do", method = {RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object getUpPdf(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		
		String fileParams = request.getParameter("fileParams");//附件上传信息
		List<Map<String, String>> fileParamsList = new ArrayList<Map<String, String>>();
		//解析附件上传信息
		if(StringUtils.isNotEmpty(fileParams)){
			JSONArray arry = JSONArray.fromObject(fileParams);
			for (int i = 0; i < arry.size(); i++) {
				net.sf.json.JSONObject jsonObject = arry.getJSONObject(i);
				Iterator<?> it = jsonObject.keys();  
				HashMap<String, String> hMap = new HashMap<String, String>();
				while (it.hasNext())  
				{  
					String key = String.valueOf(it.next());  
					String value = (String) jsonObject.get(key);  
					hMap.put(key, value);  
				} 
				fileParamsList.add(hMap);
			}
		}
		String filePath = fileParamsList.get(0).get("filePath");
		String mobilePhone= request.getParameter("mobilePhone");
		if(StringUtils.isEmpty(filePath)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("路径不能为空");
			return result;
		}
		if(StringUtils.isEmpty(mobilePhone)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("手机号不能为空");
			return result;
		}

		FilSignQueryCondition qc = new FilSignQueryCondition();
		qc.setFilePath(filePath);
		qc.setMobliePhone(mobilePhone);
		FilSignDTO dto = this.filSignService.getUpPdf(qc);
		Map<String,String> data= new HashMap<String,String>();
		data.put("path", dto.getFilePath());
		data.put("message", dto.getRebackMessage());
		result.setData(data);
		result.setInfo(dto.getFilePath());
		return result;
	}
	@RequestMapping(value = "/getPath.do", method = {RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO getPath(HttpServletRequest request, HttpServletResponse response)throws BaseException{
		BaseLogUtils.info(logger, "getPath", "进入下载文件方法");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		String contractNo = request.getParameter("contractNo");
		if(StringUtils.isEmpty(contractNo)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数为空");
		}
		FilSignDTO dto = new FilSignDTO();
		dto.setContractNo(contractNo);
		FilSignDTO resuDto = this.filSignService.downLoad(dto);
		if(resuDto != null && StringUtils.isNotEmpty(resuDto.getFilePath())){
			result.setInfo(resuDto.getFilePath());
			return result;
		}else{
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("下载文件失败");
			BaseLogUtils.info(logger, "getPath", "下载失败");
			return result;
		}
	}
}

